# Lucid is (C) Copyright 2006-2007 by Infiscape Corporation
#
# This file is part of Lucid, a PyOpenSG example application.
#
# Lucid is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# Lucid is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program.  If not, see <http://www.gnu.org/licenses/>.

# Main entry point for the application
#
import sys, os, os.path, time, traceback
pj = os.path.join

## Since usils are meant to be common, get them in the path
## XXX: Don't do this is makes types have different names for same type
#util_base_path = os.path.normpath(pj(os.path.dirname(__file__),'lucid'))
#sys.path.insert(0,util_base_path)

from PyQt4 import QtGui, QtCore, QtOpenGL

# First time for import so check it.
try:
   from OpenGL.GL import *
   from OpenGL.GLUT import *
   from OpenGL.GLU import *
except ImportError:
   app = QtGui.QApplication(sys.argv)
   QtGui.QMessageBox.critical(None, "textures.py",
                           "PyOpenGL must be installed to run this example.",
                           QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default,
                           QtGui.QMessageBox.NoButton)
   sys.exit(app.exec_())

import osg2
import lucid.core
import lucid.view
from lucid.util.debugging import hookFullTrace
from pydispatch import dispatcher
import lucid_resources


def createScene():
   max_depth = 4
   width = 3
   
   osg2.osgInit([])
   
   scene_root = osg2.Node.create()
   scene_root.setCore(osg2.Group.create())
   osg2.setName(scene_root, "R")
   
   def genTree(root, depth):
      if depth >= max_depth:
         return
         
      for x in range(width):
         new_node = osg2.Node.create()
         root.addChild(new_node)
         
         new_node.setCore(osg2.Group.create())
         osg2.setName(new_node, "%s.%s"%(osg2.getName(root),x))
         genTree(new_node, depth+1)
   
   genTree(scene_root, 0)
   return scene_root

def printSignal(signal, sender, *arg, **kw):
      sender_name = str(sender)
      sig_name = str(signal)
      arg_str = str(arg)
      kw_str = str(kw)
      
      desc = "%s [%s]: %s %s\n"%(sender_name,sig_name,arg_str,kw_str)
      print "pydispatch: ", desc
   

def main():
   #hookFullTrace()
   dispatcher.connect(printSignal)
   
   # Initialize OpenSG and Qt
   osg2.osgInit([])
   app = QtGui.QApplication(sys.argv)
      
   # --- Bootstrap the environment --- #
   splash_map = QtGui.QPixmap(pj("data","splash.png"))
   splash = QtGui.QSplashScreen(splash_map)   
   splash.show()
   splash.showMessage("Bootstrapping system...",QtCore.Qt.AlignLeft,QtCore.Qt.green)
   app.processEvents()
   
   def splashProgressCB(percent, message):
      splash.showMessage("%3.0f%% %s"%(percent*100,message), QtCore.Qt.AlignLeft, QtCore.Qt.green)
      app.processEvents()   

   # Initialize environment
   environment = lucid.core.Environment()
   environment.initialize(progressCB=splashProgressCB, dataDir=pj(os.getcwd(),"data"))

   # XXX: Should move into environment intialize in the future.
   if len(sys.argv) < 2:
      #print "Loading torus...."
      #scene = osg2.makeTorus(0.5,2,16,16)
      #osg2.setName(scene, "Root")
      scene = createScene()
      
      # HACK: For now add first scene manually
      environment.addScene(lucid.core.Scene(scene,"generated"))
   else:
      environment.openFile(sys.argv[1])      
   
   
   # Create and display GUI
   v = environment.viewer
   v.show()
   splash.finish(v)

   exit_code = None
   while None == exit_code:
      try:
         exit_code = app.exec_()
      except Exception, ex:
         print " ------------ Main Exception -----------"
         print "   exception:", ex
         traceback.print_exc()
   
   sys.exit(exit_code)

if __name__ == '__main__':
   main()
